package com.ganyu.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ganyu.domain.ResponseResult;
import com.ganyu.domain.dto.AdminRoleDto;
import com.ganyu.domain.dto.AdminUserDto;
import com.ganyu.domain.entity.Menu;
import com.ganyu.domain.entity.Role;
import com.ganyu.domain.entity.User;
import com.ganyu.domain.vo.AdminAllRoleVo;
import com.ganyu.domain.vo.AdminRoleVo;
import com.ganyu.domain.vo.AdminUserVo;
import com.ganyu.domain.vo.PageVo;
import com.ganyu.mapper.MenuMapper;
import com.ganyu.mapper.RoleMapper;
import com.ganyu.mapper.RoleMenuMapper;
import com.ganyu.service.RoleService;
import com.ganyu.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * DATA: 2022/9/30
 * Author: 晨夕
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;
    //获取角色列表

    @Override
    public ResponseResult getRoleList(Integer pageNum,Integer pageSize,String roleName,String status) {
        List<Role> roleList = roleMapper.getRoleList((pageNum-1) * pageSize,pageSize,roleName,status);
        int count = roleMapper.getCount(roleName,status);
        List<AdminRoleVo> adminRoleVos = BeanCopyUtils.copyBeanList(roleList, AdminRoleVo.class);
        PageVo<AdminRoleVo> pageVo = new PageVo<>();
        pageVo.setRows(adminRoleVos);
        pageVo.setTotal(count);
        return ResponseResult.okResult(pageVo);
    }

    //修改角色权限
    @Override
    public ResponseResult changeStatus(Long roleId ,String status) {
        roleMapper.changeStatus(roleId,status);
        return ResponseResult.okResult();
    }

    //添加角色
    @Override
    public ResponseResult addUser(AdminUserDto adminUserDto) {
        roleMapper.insertUser(adminUserDto);
        Long userId = roleMapper.getUserId(adminUserDto.getRoleName());
        for(Long menuId : adminUserDto.getMenuIds()){
            roleMenuMapper.insertMenuId(userId,menuId);
        }
        return ResponseResult.okResult();
    }

    //根据id查询角色信息
    @Override
    public ResponseResult selectUserById(Long id) {
        Role role = roleMapper.selectById(id);
        AdminUserVo adminUserVo = BeanCopyUtils.copyBean(role, AdminUserVo.class);
        return ResponseResult.okResult(adminUserVo);
    }

    @Override
    public ResponseResult deleteUser(Long[] ids) {
        roleMapper.deleteUserById(ids);
        return ResponseResult.okResult();
    }

    //查找正常状态的role
    @Override
    public ResponseResult selectAllRole() {
        List<AdminAllRoleVo> adminAllRoleVos = roleMapper.selectAllRole();
        return ResponseResult.okResult(adminAllRoleVos);
    }
}
